package com.dzt.cloudreader.network;

import android.content.Context;
import android.content.Intent;

import com.dzt.cloudreader.model.BookBean;
import com.dzt.cloudreader.model.BookDetailBean;
import com.dzt.cloudreader.mvp.MvpPresenter;
import com.dzt.cloudreader.mvp.MvpView;
import com.dzt.cloudreader.utils.JLogKit;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by M02323 on 2017/12/28.
 */

public class BookPresenter implements MvpPresenter {
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private Context mContext;
    private BookView bookView;
    private BookBean bookBean;

    public BookPresenter(Context context) {
        mContext = context;
    }

    @Override
    public void onCreate() {
        manager = DataManager.getInstance();
        mCompositeSubscription = new CompositeSubscription();
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {

    }

    @Override
    public void onDestroy() {
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    public void attachView(MvpView view) {
        bookView = (BookView) view;
    }

    @Override
    public void attachIncomingIntent(Intent intent) {

    }

    public void getBook(String tag, int start, int count) {
        mCompositeSubscription.add(manager.getBook(tag, start, count)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BookBean>() {
                    @Override
                    public void onCompleted() {
                        JLogKit.getInstance().e("onCompleted");
                        if (bookBean != null) {
                            bookView.onSuccess(bookBean);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        bookView.onError("请求失败！！");
                        JLogKit.getInstance().e("onError");
                    }

                    @Override
                    public void onNext(BookBean movieBean) {
                        JLogKit.getInstance().e("onNext");
                        BookPresenter.this.bookBean = movieBean;
                    }
                }));
    }
}
